package cn.wolfcode.luowowo.commment.service.impl;


import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.commment.repository.ITravelCommentRepository;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {
    @Autowired
    private ITravelCommentRepository repository;

    @Autowired
    private MongoTemplate mongoTemplate;



    @Override
    public TravelComment save(TravelComment comment) {
        if (!StringUtils.hasLength(comment.getId())){
            comment.setCreateTime(new Date());
        }

        //必须处理引用评论
        String refId = comment.getRefComment().getId();
        if(StringUtils.hasLength(refId)){
            TravelComment ref =repository.findById(refId).get();
            comment.setRefComment(ref);
        }
        repository.save(comment);
        return comment;
    }

    @Override
    public Page query(TravelCommentQuery qo) {
        //repository mongoTemplale 无法直接查询出page分页数据对象,需要自己手动封装
        //拼接条件
        Query query = new Query();
        if(qo.getTravelId()!=-1){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }
        //查询总条数
        long total = mongoTemplate.count(query, TravelComment.class);
        if(total==0){
            return Page.empty();//返回空对象
        }
        //查询当前页显示list
        //注意需要设置分页信息以及排序信息
        //参数1:当前页,从0开始
        //参数2:每页显示的调试
        //参数3:排序规则
        //参数4:排序的字段
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(),
                Sort.Direction.ASC,"createTime");
        query.with(pageable);
        List<TravelComment> list = mongoTemplate.find(query, TravelComment.class);
        return new PageImpl(list,pageable,total);
    }

    @Override
    public Long getCount(Long travelId) {
        Query query = new Query();
        if(travelId!=null){
            query.addCriteria(Criteria.where("travelId").is(travelId));
        }
        //查询总条数
        long count = mongoTemplate.count(query, TravelComment.class);
        return count;
    }


}
